<template>
  <view class="login-container">
    <uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
    <!-- <button type="primary" class="btn-login" open-type="getUserInfo" @getuserinfo="getUserInfo">一键登录</button> -->
    <button type="primary" class="btn-login" @click="getUserProfile">一键登录</button>
    <!-- <button type="primary" class="btn-login" open-type="getPhoneNumber" @getPhoneNumber="getPhone">授权手机号登录</button> -->

    <text class="tips-text">登录后尽享更多权益</text>
  </view>
</template>

<script>
  import {
    mapMutations,
    mapState
  } from 'vuex'


  export default {
    data() {
      return {
        userInfo: {}
      };
    },
    computed: {
      ...mapState('m_user', ['redirectInfo'])
    },
    methods: {
      ...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'updateRedirectInfo']),
      // 用户授权之后，获取用户的基本信息
      getUserInfo(e) {
        console.log(e)

        if (e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$showMsg('您取消了登录授权！')

        console.log(e.detail.userInfo)
        this.updateUserInfo(e.detail.userInfo)

        this.getToken(e.detail)
      },
      async getToken(info) {
        // 调用微信登录接口
        const [err, res] = await uni.login().catch(err => err)
        // 判断是否 uni.login() 调用失败
        console.log('getToken', res)
        if (err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败了，请重试！')
        console.log('res', res)
        // 准备参数
        const query = {
          code: res.code,
          encryptedData: info.encryptedData,
          iv: info.iv,
          rawData: info.rawData,
          signature: info.signature
        }

        const {
          data: loginResult
        } = await uni.$http.post('/api/public/v1/users/wxlogin', query)
        console.log(loginResult)
        if (loginResult.meta.status !== 200) return uni.$showMsg('登录失败！')

        // 直接把 token 保存到 vuex 中
        this.updateToken(loginResult.message.token)
        this.navigateBack()
      },
      navigateBack() {
        if (this.redirectInfo && this.redirectInfo.openType === 'switchTab') {
          uni.switchTab({
            url: this.redirectInfo.from,
            complete: () => {
              // 导航成功之后，把 vuex 中的 redirectInfo 对象重置为 null
              this.updateRedirectInfo(null)
            }
          })
        }
      },
      // 获取手机号
      getPhone(e) {
        const getPhoneCode = e.detail.code
        uni.login({
          provider: 'weixin',
          success: (res) => {
            console.log('res-login', res);
            //获取到code
            this.code = res.code;
            // console.log('code', res.code);
            //请求登录接口
            if (res.errMsg == 'login:ok') {
              let query = {
                grant_type: 'urn:ietf:params:oauth:grant-type:wechat',
                scope: 'message.write openid',
                code: this.code,
                role: 'user',
                getPhoneCode: getPhoneCode
              }
              this.wechatLogin(query)
            }
          },
        });
      },
      // 微信登录
      async wechatLogin(query) {
        const {
          data: loginResult
        } = await uni.$http.post('/api/public/v1/users/wxlogin', query)
        console.log(loginResult)
        if (loginResult.meta.status !== 200) return uni.$showMsg('登录失败！')

        if (res.statusCode == 200 && res.data.code !== 0) {
          uni.showToast({
            title: '登录成功',
            icon: 'success',
            mask: true,
          });
          //获取到token 存入缓存。通过有无token来判断是否登录
          // 直接把 token 保存到 vuex 中
          this.updateToken(res.data.access_token)
          // 刷新当前页面
          uni.reLaunch({
            url: '/pages/my/my'
          });
        } else {
          uni.showToast({
            title: '登录失败',
            icon: 'warn',
            mask: true,
          });
        }
      },
      async getUserProfile(e) {
        // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
        // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
        const [err, res] = await uni.getUserProfile({
          desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        }).catch(err => err)
        console.log('getUserProfile', res)
        // 判断是否 uni.login() 调用失败
        if (err || res.errMsg !== 'getUserProfile:ok') return uni.$showMsg('登录失败了，请重试！')
        this.updateUserInfo(res.userInfo)

        this.getToken(res)
      },

    }
  }
</script>

<style lang="scss">
  .login-container {
    height: 750rpx;
    background-color: #F8F8F8;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
    overflow: hidden;

    &::after {
      content: ' ';
      display: block;
      width: 100%;
      height: 40px;
      background-color: white;
      position: absolute;
      bottom: 0;
      left: 0;
      border-radius: 100%;
      transform: translateY(50%);
    }

    .btn-login {
      width: 90%;
      border-radius: 100px;
      margin: 15px 0;
      background-color: #C00000;
    }

    .tips-text {
      font-size: 12px;
      color: gray;
    }
  }
</style>